<template>
    <page-container>
        <div class="ant-pro-table">
            <div class="ant-pro-table-search">
                <a-form layout="horizontal">
                    <a-row :gutter="16" type="flex" justify="start">
                        <a-col :xs="12" :sm="12" :md="4">
                            <a-form-item hide-label>
                                <a-input-search placeholder="输入关键词名称" v-model:value="queryParams.word" allow-clear enter-button @search="handleSearch()" />
                            </a-form-item>
                        </a-col>
                        <a-col :xs="12" :sm="12" :md="4">
                            <a-form-item hide-label>
                                <a-input-search placeholder="输入创建人姓名" v-model:value="queryParams.creator" allow-clear enter-button @search="handleSearch()" />
                            </a-form-item>
                        </a-col>
                        <a-col :xs="12" :sm="12" :md="3">
                            <a-form-item hide-label>
                                <a-select v-model:value="queryParams.wordClassId" @change="handleSearch()" placeholder="词性" :options="dictTypes"></a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="12" :lg="3">
                            <!-- <a-button @click="handleSearch" type="primary">搜索</a-button> -->
                            <a-button @click="handleReset" class="ml-5px">重置</a-button>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="12" :lg="4">
                            <a-button @click="handleBatch(1)" type="primary">启用选中</a-button>
                            <a-button danger @click="handleBatch(2)" class="ml-5px">停用选中</a-button>
                        </a-col>
                        <a-col :span="4">
                            <div class="ant-pro-table-list-toolbar-right">
                                <a-space align="center">
                                    <a-button type="primary" v-permission="[`system:menu:create`]" @click="dialogModalRef.init()">
                                        <plus-outlined />
                                        新增
                                    </a-button>
                                </a-space>
                                <div class="ant-pro-table-list-toolbar-divider">
                                    <a-divider type="vertical" />
                                </div>
                                <div class="ant-pro-table-list-toolbar-setting-item">
                                    <a-tooltip title="刷新">
                                        <reload-outlined @click="reload" />
                                    </a-tooltip>
                                </div>

                                <div class="ant-pro-table-list-toolbar-setting-item">
                                    <a-popover placement="bottomRight" arrowPointAtCenter trigger="click" overlayClassName="ant-pro-table-column-setting-overlay">
                                        <template #title>
                                            <div class="ant-pro-table-column-setting-title">
                                                <a-checkbox v-model:checked="columnState.checkAll" :indeterminate="columnState.indeterminate" @change="handleColumnAllClick">
                                                    列展示 / 排序
                                                </a-checkbox>
                                                <a @click="reset">重置</a>
                                            </div>
                                        </template>
                                        <template #content>
                                            <span class="ant-pro-table-column-setting-list">
                                                <drag-container
                                                    lockAxis="y"
                                                    dragClass="ant-pro-table-drag-ghost"
                                                    dropClass="ant-pro-table-drop-ghost"
                                                    @drop="({ removedIndex, addedIndex }) => move(removedIndex, addedIndex)"
                                                >
                                                    <template :key="column.key" v-for="column in dynamicColumnItems">
                                                        <draggable>
                                                            <div class="ant-pro-table-column-setting-list-item">
                                                                <drag-icon />
                                                                <a-checkbox :checked="column.checked" @change="handleColumnChange($event, column)">
                                                                    {{ column.label }}
                                                                </a-checkbox>
                                                            </div>
                                                        </draggable>
                                                    </template>
                                                </drag-container>
                                            </span>
                                        </template>
                                        <a-tooltip title="列设置">
                                            <setting-outlined />
                                        </a-tooltip>
                                    </a-popover>
                                </div>
                            </div>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
            <a-card :body-style="{ padding: 0 }" ref="elRef">
                <a-table
                    row-key="id"
                    :row-selection="rowSelection"
                    :size="state.tableSize"
                    :loading="state.loading"
                    :columns="dynamicColumns"
                    :data-source="state.dataSource"
                    :pagination="{
                        showSizeChanger: true,
                        current: state.current,
                        pageSize: state.pageSize,
                        total: state.total,
                        showTotal: total => `共 ${total} 条`,
                    }"
                    @change="handleTableChange"
                >
                    <!-- <template #expandedRowRender="{ record }">
                        <div class="table-role-permission-card">
                            <a-row :gutter="12">
                                <a-col style="height: 48px" :span="12" :key="permission.id" v-for="permission in record.permissions">
                                    <a-row :gutter="16">
                                        <a-col :span="4">{{ permission.label }}</a-col>
                                        <a-col>
                                            <a-tag color="cyan" :key="action" v-for="action in permission.actions">
                                                {{ action }}
                                            </a-tag>
                                        </a-col>
                                    </a-row>
                                </a-col>
                            </a-row>
                        </div>
                    </template> -->
                    <template #bodyCell="{ record, column }">
                        <template v-if="column.dataIndex === 'status'">
                            <a-tag :color="statusMap[record.status ? 1 : 0]?.status">{{ statusMap[record.status ? 1 : 0]?.text }}</a-tag>
                        </template>
                        <template v-if="column.dataIndex === 'action'">
                            <a-space>
                                <a @click="handleEdit(record)" v-permission="[`system:menu:update`]">编辑</a>
                                <a-popconfirm title="确定要删除吗 ?" @confirm="onDelete(record)">
                                    <a-button type="text" danger size="small" v-permission="[`system:menu:delete`]">删除</a-button>
                                </a-popconfirm>
                            </a-space>
                        </template>
                    </template>
                </a-table>
            </a-card>
        </div>
        <dialog-modal ref="dialogModalRef" @success="reload" />
    </page-container>
</template>

<script lang="ts" setup>
    import { reactive, ref, onMounted } from 'vue';
    import { PlusOutlined, ReloadOutlined, ColumnHeightOutlined, SettingOutlined, FullscreenOutlined, FullscreenExitOutlined } from '@ant-design/icons-vue';
    import { Container as DragContainer, Draggable } from '@/components/draggable';
    import { dictDataListByDictType } from '@/api/user/dict';
    import type { Pagination, TableColumn } from '@/typing';
    import { useFetchData } from '@/utils/hooks/useFetchData';
    import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
    import DragIcon from '@/components/table/drag-icon.vue';
    import { getSensitiveWordsPage, deleteSensitiveWords, getSensitiveWordsStatus } from '@/api/smss/keyword';
    import dialogModal from './components/dialog-modal.vue';
    import { message } from 'ant-design-vue';
    import type { TableProps } from 'ant-design-vue';

    const baseColumns: TableColumn[] = [
        {
            title: '关键词',
            dataIndex: 'word',
        },
        {
            title: '词性',
            dataIndex: 'wordClass',
        },
        {
            title: '员工触发次数',
            dataIndex: 'staffTriggerCount',
        },
        {
            title: '客户触发次数',
            dataIndex: 'ownerTriggerCount',
        },
        {
            title: '状态',
            dataIndex: 'status',
        },
        {
            title: '创建人',
            dataIndex: 'userName',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
        },
        {
            title: '操作',
            dataIndex: 'action',
        },
    ];

    const {
        state: columnState,
        dynamicColumns,
        dynamicColumnItems,
        handleColumnAllClick,
        handleColumnChange,
        reset,
        move,
    } = useTableDynamicColumns(baseColumns, { needRowIndex: false });
    const queryParams = reactive<any>({});
    const fetchDataContext = reactive({
        current: 1,
        pageSize: 10,
        tableSize: 'middle', // 'default' | 'middle' | 'small'
        stripe: true,
        executeImmediately: false,
        isList: false,
        requestParams: {
            ...queryParams,
        },
    });
    const statusMap = {
        0: { text: '停用', status: 'error' },
        1: { text: '正常', status: 'processing' },
    };
    // 表格数据和加载
    const { context: state, reload } = useFetchData(getSensitiveWordsPage, fetchDataContext);

    const dialogModalRef = ref();
    const dictTypes = ref<any>([]);

    onMounted(async () => {
        // 重置
        const responseData: any = await dictDataListByDictType({
            dictType: 'word_class',
        });
        dictTypes.value = responseData.data;
        fetchDataContext.executeImmediately = true;
        reset();
    });

    const formatDict = val => {
        return dictTypes.value.find(item => item.value === val)?.label;
    };

    const handleTableChange = ({ current, pageSize }: Pagination) => {
        fetchDataContext.current = current;
        fetchDataContext.pageSize = pageSize;
    };

    const handleEdit = (record: Record<string, any>) => {
        dialogModalRef.value.init(record);
    };
    const onDelete = (data: any) => {
        deleteSensitiveWords(data.id).then(res => {
            if (res.code === 200) {
                message.success('删除成功');
                reload();
            }
        });
    };

    const batchList: any = ref([]);
    const batchLists: any = ref([]);
    const rowSelection: TableProps['rowSelection'] = {
        // preserveSelectedRowKeys: true,
        selectedRowKeys: batchList,
        onChange: (selectedRowKeys: string[], selectedRows: any) => {
            batchLists.value = selectedRows;
            batchList.value = selectedRowKeys;
        },
        getCheckboxProps: item => ({
            disabled: item.inspectionWay == 1,
        }),
    };

    const handleBatch = (type: number) => {
        if (batchList.value.length === 0) {
            message.warning('请选择要操作的数据');
            return false;
        }
        getSensitiveWordsStatus({
            status: type === 1 ? 1 : 0,
            ids: batchList.value,
        }).then(res => {
            if (res.code === 200) {
                message.success('操作成功');
                batchLists.value = [];
                batchList.value = [];
                reload();
            }
        });
    };

    const handleSearch = () => {
        fetchDataContext.current = 1;
        fetchDataContext.requestParams = { ...queryParams };
    };
    const handleReset = () => {
        Object.keys(queryParams).forEach(key => {
            delete queryParams[key];
        });
        handleSearch();
    };
</script>
